package org.jacp.demo.ui.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JComponent;
import javax.swing.Timer;
import javax.swing.TransferHandler;

import org.jacp.demo.util.DropShadowPanel;

public class DropShadowPanelMouseListener extends MouseAdapter implements
	ActionListener {
    @Override
    public void mousePressed(final MouseEvent e) {
	final JComponent jc = (JComponent) e.getSource();
	final TransferHandler th = jc.getTransferHandler();
	th.exportAsDrag(jc, e, TransferHandler.COPY);
	mouseClicked(e);
    }

    MouseEvent lastEvent;
    private final static int delay = 250;
    Timer timer;
    long time;
    private String fileName;
    private DropShadowPanel parentPanel;

    public DropShadowPanelMouseListener() {
	this(delay);
	time = System.currentTimeMillis();
    }

    public DropShadowPanelMouseListener(final String fileName) {
	this(delay);
	time = System.currentTimeMillis();
	this.fileName = fileName;
    }

    public DropShadowPanelMouseListener(final String fileName,
	    final DropShadowPanel parentPanel) {
	this(delay);
	time = System.currentTimeMillis();
	this.fileName = fileName;
	this.parentPanel = parentPanel;
    }

    public DropShadowPanelMouseListener(final int delay) {
	timer = new Timer(delay, this);
    }

    @Override
    public void mouseClicked(final MouseEvent e) {
	if (e.getClickCount() > 2) {
	    return;
	}
	lastEvent = e;
	if (timer.isRunning()) {
	    timer.stop();
	    doubleClick(lastEvent);
	} else {
	    timer.restart();
	}
    }

    @Override
    public void actionPerformed(final ActionEvent e) {
	timer.stop();
	singleClick(lastEvent);
    }

    public void singleClick(final MouseEvent e) {
	System.out.println("single1: " + fileName);
    }

    public void doubleClick(final MouseEvent e) {
	System.out.println("double1: " + fileName);
	parentPanel.handleDoubleClick();
    }

}
